#!/usr/bin/env bash
# create time: 2017-12-08 14:51
# create by: Wu Chengbo
# desc: 部署到K8S

set -eo pipefail

KUBE_NAMESPACE="`kubectl config view -o jsonpath=\"{ .contexts[0].context.namespace }\"`"

name="${CI_PROJECT_NAME//_/-}-${CI_ENVIRONMENT_SLUG}"

echo "项目名称: ${name}"
echo "项目所在命名空间: ${KUBE_NAMESPACE}"

echo "Deploying ${CI_ENVIRONMENT_SLUG} (replicas: ${replicas}) with ${TARGET_IMG_NAME}:${CI_COMMIT_REF_NAME}..."
cat <<EOF > k8s.yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: ${name}
  labels:
    app: ${name}
    pipeline_id: "${CI_PIPELINE_ID}"
    build_id: "${CI_BUILD_ID}"
spec:
  minReadySeconds: 5
  replicas: ${REPLICAS_NUM}
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  template:
    metadata:
      labels:
        app: ${name}
    spec:
      containers:
        - name: base
          image: ${TARGET_IMG_NAME}:${CI_ENVIRONMENT_SLUG}
          resources:
            limits:
              memory: ${LIMIT_M}
          env:
          - name: IM_PRJ
            value: ${CI_PROJECT_NAME}
          - name: SRV_RUN_NAME
            value: ${SRV_RUN_NAME}
          - name: DEPLOY_TIMESTAMP
            value: "`date +%s`"
          readinessProbe: &healthChecking
            initialDelaySeconds: 60
            periodSeconds: 5
            successThreshold: 1
            failureThreshold: 8
            httpGet:
              path: /health
              port: 2601
              httpHeaders:
              - name: X-Checking-Health
                value: k8s
          livenessProbe:
            <<: *healthChecking
          imagePullPolicy: Always
          ports:
            - containerPort: 2601
          volumeMounts:
          - mountPath: /var/log/${SRV_RUN_NAME}
            name: log
          - mountPath: /var/opt/wx_pay
            name: wx-pay
      volumes:
      - name: log
        hostPath:
          path: /var/log/${SRV_RUN_NAME}/${CI_ENVIRONMENT_SLUG}
      - name: wx-pay
        hostPath:
          path: /var/opt/wx_pay

---
apiVersion: v1
kind: Service
metadata:
  name: ${name}
  labels:
    app: ${name}
spec:
  ports:
    - port: 5000
      targetPort: 2601
  selector:
    app: ${name}

---
EOF

cat k8s.yaml
kubectl apply -f k8s.yaml

echo "Waiting for deployment..."
kubectl rollout status -w "deployment/${name}"



